import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:xindong/utils/xindong_cache_util.dart';
import 'package:svgaplayer_flutter/svgaplayer_flutter.dart';

/// SVGA动画 SVGASimpleImage
class XinDongAnimationSVGA extends StatefulWidget {
  final String url;
  final BoxFit fit;
  final Function() onPlayEnd;

  const XinDongAnimationSVGA({Key? key, required this.url, required this.onPlayEnd, this.fit = BoxFit.fitWidth})
      : super(key: key);

  @override
  State<XinDongAnimationSVGA> createState() => _XinDongAnimationSVGAState();
}

class _XinDongAnimationSVGAState extends State<XinDongAnimationSVGA> with SingleTickerProviderStateMixin {
  late SVGAAnimationController animationController;
  late MovieEntity videoItem;

  @override
  void initState() {
    super.initState();
    animationController = SVGAAnimationController(vsync: this);
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  /// 加载动画
  void loadAnimation() async {
    try {
      // 缓存
      File file = await XinDongCacheSingleton.instance.getSingleFile(widget.url);
      videoItem = await SVGAParser.shared.decodeFromBuffer(file.readAsBytesSync());

      // 先重置，避免下次无效果
      animationController.reset();

      // 设置动画项
      animationController.videoItem = videoItem;

      // 向前动画// Try to use .forward() .reverse() .repeat()
      animationController.forward().whenComplete(() {
        animationController.videoItem = null;
        widget.onPlayEnd();
      });
    } catch (e) {
      widget.onPlayEnd();
    }
  }

  @override
  Widget build(BuildContext context) {
    loadAnimation();
    return SVGAImage(animationController, fit: widget.fit);
  }
}
